<template>
  <div class="stats-dashboard">
    <el-row :gutter="20" class="dashboard-row">
      <!-- Summary Cards -->
      <el-col :xs="24" :sm="12" :md="6" :lg="6" v-for="(stat, index) in summaryStats" :key="'stat-'+index">
        <el-card shadow="hover" class="summary-card" :class="stat.type">
          <div class="card-icon">
            <i :class="stat.icon"></i>
          </div>
          <div class="card-content">
            <div class="card-value">{{ stat.value }}</div>
            <div class="card-label">{{ stat.label }}</div>
          </div>
          <div class="card-trend" v-if="stat.trend">
            <span :class="{'up': stat.trend > 0, 'down': stat.trend < 0}">
              <i :class="stat.trend > 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
              {{ Math.abs(stat.trend) }}%
            </span>
            相比上月
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="dashboard-row">
      <!-- Hour Heatmap Chart -->
      <el-col :xs="24" :sm="24" :md="12">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="chart-header">
            <span>借阅时段热力图</span>
            <el-dropdown trigger="click" @command="handleHeatmapPeriodChange">
              <el-button type="text" size="small">
                {{ heatmapPeriod }} <i class="el-icon-arrow-down"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="最近7天">最近7天</el-dropdown-item>
                <el-dropdown-item command="最近30天">最近30天</el-dropdown-item>
                <el-dropdown-item command="今年">今年</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
          <div class="chart-container">
            <div ref="heatmapChart" class="chart"></div>
          </div>
        </el-card>
      </el-col>

      <!-- Category Statistics Pie Chart -->
      <el-col :xs="24" :sm="24" :md="12">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="chart-header">
            <span>图书分类统计</span>
            <el-radio-group v-model="categoryChartType" size="small" @change="updateCategoryChart">
              <el-radio-button label="borrow">借阅量</el-radio-button>
              <el-radio-button label="collection">馆藏量</el-radio-button>
            </el-radio-group>
          </div>
          <div class="chart-container">
            <div ref="categoryChart" class="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="dashboard-row">
      <!-- Borrow Trend Line Chart -->
      <el-col :span="24">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="chart-header">
            <span>借阅趋势</span>
            <el-radio-group v-model="trendPeriod" size="small" @change="updateTrendChart">
              <el-radio-button label="week">周</el-radio-button>
              <el-radio-button label="month">月</el-radio-button>
              <el-radio-button label="year">年</el-radio-button>
            </el-radio-group>
          </div>
          <div class="chart-container large">
            <div ref="trendChart" class="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="dashboard-row">
      <!-- Popular Books Table -->
      <el-col :span="24">
        <el-card shadow="hover" class="table-card">
          <div slot="header" class="chart-header">
            <span>热门图书排行</span>
            <el-tabs v-model="popularBooksTab" size="small" @tab-click="handlePopularTabChange">
              <el-tab-pane label="本周" name="week"></el-tab-pane>
              <el-tab-pane label="本月" name="month"></el-tab-pane>
              <el-tab-pane label="本年" name="year"></el-tab-pane>
            </el-tabs>
          </div>
          <el-table :data="popularBooks" style="width: 100%" :row-class-name="tableRowClassName">
            <el-table-column type="index" width="50" align="center"></el-table-column>
            <el-table-column label="封面" width="80">
              <template slot-scope="scope">
                <img 
                  v-if="scope.row.coverUrl" 
                  :src="scope.row.coverUrl" 
                  alt="Cover" 
                  class="book-cover-small"
                >
                <div v-else class="cover-placeholder-small">
                  <i class="el-icon-notebook-2"></i>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="title" label="书名"></el-table-column>
            <el-table-column prop="author" label="作者" width="150"></el-table-column>
            <el-table-column prop="category" label="分类" width="120"></el-table-column>
            <el-table-column prop="borrowCount" label="借阅次数" width="100" align="center">
              <template slot-scope="scope">
                <el-badge :value="scope.row.borrowCount" class="borrow-badge"></el-badge>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" align="center">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="viewBookDetail(scope.row)">查看详情</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'StatsDashboard',
  data() {
    return {
      summaryStats: [
        { 
          label: '今日借出', 
          value: 42, 
          icon: 'el-icon-upload2', 
          type: 'primary',
          trend: 5
        },
        { 
          label: '今日归还', 
          value: 38, 
          icon: 'el-icon-download', 
          type: 'success',
          trend: 3
        },
        { 
          label: '逾期未还', 
          value: 17, 
          icon: 'el-icon-warning', 
          type: 'danger',
          trend: -2
        },
        { 
          label: '总借阅量', 
          value: '4,521', 
          icon: 'el-icon-data-analysis', 
          type: 'info',
          trend: 12
        }
      ],
      heatmapPeriod: '最近7天',
      categoryChartType: 'borrow',
      trendPeriod: 'month',
      popularBooksTab: 'week',
      popularBooks: [],
      heatmapChart: null,
      categoryChart: null,
      trendChart: null
    }
  },
  mounted() {
    this.initHeatmapChart()
    this.initCategoryChart()
    this.initTrendChart()
    this.fetchPopularBooks()
    
    // Add window resize listener
    window.addEventListener('resize', this.resizeCharts)
  },
  beforeDestroy() {
    // Remove window resize listener
    window.removeEventListener('resize', this.resizeCharts)
    
    // Dispose charts
    this.heatmapChart && this.heatmapChart.dispose()
    this.categoryChart && this.categoryChart.dispose()
    this.trendChart && this.trendChart.dispose()
  },
  methods: {
    resizeCharts() {
      this.heatmapChart && this.heatmapChart.resize()
      this.categoryChart && this.categoryChart.resize()
      this.trendChart && this.trendChart.resize()
    },
    
    // Heatmap chart
    initHeatmapChart() {
      this.heatmapChart = echarts.init(this.$refs.heatmapChart)
      this.updateHeatmapChart()
    },
    updateHeatmapChart() {
      // Generate some demo data
      const hours = ['0:00', '2:00', '4:00', '6:00', '8:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00', '22:00']
      const days = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      
      const data = []
      for (let i = 0; i < days.length; i++) {
        for (let j = 0; j < hours.length; j++) {
          // Generate random data - in a real app this would come from your API
          data.push([j, i, Math.round(Math.random() * 10) * (i + 1)])
        }
      }
      
      const option = {
        tooltip: {
          position: 'top',
          formatter: (params) => {
            return `${days[params.value[1]]} ${hours[params.value[0]]}<br>借阅量: ${params.value[2]}`
          }
        },
        grid: {
          top: '10%',
          left: '5%',
          right: '5%',
          bottom: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: hours,
          splitArea: {
            show: true
          }
        },
        yAxis: {
          type: 'category',
          data: days,
          splitArea: {
            show: true
          }
        },
        visualMap: {
          min: 0,
          max: 70,
          calculable: true,
          orient: 'horizontal',
          left: 'center',
          bottom: '0%',
          inRange: {
            color: ['#e9f7fe', '#bae7ff', '#91d5ff', '#69c0ff', '#40a9ff', '#1890ff', '#096dd9']
          }
        },
        series: [{
          name: '借阅量',
          type: 'heatmap',
          data: data,
          label: {
            show: false
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      }
      
      this.heatmapChart.setOption(option)
    },
    handleHeatmapPeriodChange(period) {
      this.heatmapPeriod = period
      this.updateHeatmapChart()
    },
    
    // Category chart
    initCategoryChart() {
      this.categoryChart = echarts.init(this.$refs.categoryChart)
      this.updateCategoryChart()
    },
    updateCategoryChart() {
      const isCollection = this.categoryChartType === 'collection'
      
      // Demo data
      const data = [
        { value: isCollection ? 1048 : 234, name: '文学' },
        { value: isCollection ? 735 : 185, name: '科学技术' },
        { value: isCollection ? 580 : 300, name: '社会科学' },
        { value: isCollection ? 484 : 150, name: '艺术' },
        { value: isCollection ? 300 : 100, name: '历史' }
      ]
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'horizontal',
          bottom: 10,
          data: data.map(item => item.name)
        },
        series: [
          {
            name: isCollection ? '馆藏量' : '借阅量',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 8,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: data,
            color: ['#2A3B4D', '#5C8D89', '#D4AF37', '#E05151', '#5470c6']
          }
        ]
      }
      
      this.categoryChart.setOption(option)
    },
    
    // Trend chart
    initTrendChart() {
      this.trendChart = echarts.init(this.$refs.trendChart)
      this.updateTrendChart()
    },
    updateTrendChart() {
      // Generate dates based on period
      const dates = []
      const now = new Date()
      const borrowData = []
      const returnData = []
      
      if (this.trendPeriod === 'week') {
        // Last 7 days
        for (let i = 6; i >= 0; i--) {
          const date = new Date()
          date.setDate(now.getDate() - i)
          dates.push(`${date.getMonth() + 1}/${date.getDate()}`)
          
          // Random data
          borrowData.push(Math.floor(Math.random() * 50) + 20)
          returnData.push(Math.floor(Math.random() * 40) + 15)
        }
      } else if (this.trendPeriod === 'month') {
        // Last 30 days
        for (let i = 29; i >= 0; i--) {
          const date = new Date()
          date.setDate(now.getDate() - i)
          dates.push(`${date.getMonth() + 1}/${date.getDate()}`)
          
          // Random data with some trend
          const base = Math.sin(i * 0.1) * 10 + 25
          borrowData.push(Math.floor(Math.random() * 15) + base)
          returnData.push(Math.floor(Math.random() * 15) + (base - 5))
        }
      } else {
        // Year - by month
        for (let i = 0; i < 12; i++) {
          dates.push(`${i + 1}月`)
          
          // Random data with seasonal pattern
          const seasonalFactor = 1 + 0.3 * Math.sin((i / 11) * Math.PI * 2)
          borrowData.push(Math.floor((Math.random() * 200 + 400) * seasonalFactor))
          returnData.push(Math.floor((Math.random() * 180 + 380) * seasonalFactor))
        }
      }
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['借出量', '归还量']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dates
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '借出量',
            type: 'line',
            smooth: true,
            data: borrowData,
            symbolSize: 6,
            itemStyle: {
              color: '#2A3B4D'
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: 'rgba(42, 59, 77, 0.3)'
                }, {
                  offset: 1, color: 'rgba(42, 59, 77, 0.1)'
                }]
              }
            }
          },
          {
            name: '归还量',
            type: 'line',
            smooth: true,
            data: returnData,
            symbolSize: 6,
            itemStyle: {
              color: '#5C8D89'
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: 'rgba(92, 141, 137, 0.3)'
                }, {
                  offset: 1, color: 'rgba(92, 141, 137, 0.1)'
                }]
              }
            }
          }
        ]
      }
      
      this.trendChart.setOption(option)
    },
    
    // Popular books
    fetchPopularBooks() {
      // Mock data - in a real app, fetch from API
      this.popularBooks = [
        {
          id: 1,
          title: '百年孤独',
          author: '加西亚·马尔克斯',
          category: '文学',
          borrowCount: 156,
          coverUrl: ''
        },
        {
          id: 2,
          title: '人工智能：一种现代方法',
          author: 'Stuart Russell',
          category: '科学技术',
          borrowCount: 98,
          coverUrl: ''
        },
        {
          id: 3,
          title: '哲学导论',
          author: '罗素',
          category: '哲学',
          borrowCount: 87,
          coverUrl: ''
        },
        {
          id: 4,
          title: '小王子',
          author: '安东尼·德·圣-埃克苏佩里',
          category: '文学',
          borrowCount: 76,
          coverUrl: ''
        },
        {
          id: 5,
          title: '活着',
          author: '余华',
          category: '文学',
          borrowCount: 65,
          coverUrl: ''
        }
      ]
    },
    handlePopularTabChange() {
      this.fetchPopularBooks()
    },
    viewBookDetail(book) {
      this.$emit('view-book', book.id)
    },
    tableRowClassName({row, rowIndex}) {
      if (rowIndex === 0) {
        return 'top-row'
      } else if (rowIndex === 1) {
        return 'second-row'
      } else if (rowIndex === 2) {
        return 'third-row'
      }
      return ''
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/variables.scss";

.stats-dashboard {
  .dashboard-row {
    margin-bottom: 20px;
  }
  
  .summary-card {
    height: 110px;
    display: flex;
    align-items: center;
    border-radius: 8px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
    transition: transform 0.3s cubic-bezier(.25,.1,.25,1), box-shadow 0.3s cubic-bezier(.25,.1,.25,1);
    padding: 15px;
    border-top: none;
    border-bottom: none;
    border-right: none;
    margin-bottom: 15px;
    
    &:hover {
      transform: translateY(-3px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }
    
    &.primary {
      border-left: 4px solid $deepBlue;
      .card-icon i {
        color: $deepBlue;
      }
    }
    
    &.success {
      border-left: 4px solid $ecoGreen;
      .card-icon i {
        color: $ecoGreen;
      }
    }
    
    &.danger {
      border-left: 4px solid #F56C6C;
      .card-icon i {
        color: #F56C6C;
      }
    }
    
    &.info {
      border-left: 4px solid $goldAccent;
      .card-icon i {
        color: $goldAccent;
      }
    }
    
    .card-icon {
      font-size: 36px;
      margin-right: 15px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    .card-content {
      flex: 1;
      
      .card-value {
        font-size: 22px;
        font-weight: 600;
        font-family: 'Montserrat', sans-serif;
        color: $deepBlue;
        margin-bottom: 4px;
      }
      
      .card-label {
        font-size: 13px;
        color: $graphiteGray;
        font-family: 'Roboto', sans-serif;
      }
    }
    
    .card-trend {
      font-size: 12px;
      font-family: 'Roboto', sans-serif;
      color: $graphiteGray;
      
      span {
        margin-right: 4px;
        
        &.up {
          color: $ecoGreen;
        }
        
        &.down {
          color: #F56C6C;
        }
      }
    }
  }
  
  .chart-card, .table-card {
    margin-bottom: 15px;
    border-radius: 8px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
    transition: box-shadow 0.3s cubic-bezier(.25,.1,.25,1);
    overflow: hidden;
    
    &:hover {
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }
    
    .chart-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      span {
        font-family: 'Montserrat', sans-serif;
        font-weight: 600;
        font-size: 15px;
        color: $deepBlue;
      }
    }
    
    .chart-container {
      height: 280px;
      width: 100%;
      
      &.large {
        height: 350px;
      }
      
      .chart {
        height: 100%;
        width: 100%;
      }
    }
  }
  
  .book-cover-small {
    width: 36px;
    height: 54px;
    object-fit: cover;
    border-radius: 4px;
  }
  
  .cover-placeholder-small {
    width: 36px;
    height: 54px;
    background: linear-gradient(135deg, $deepBlue 0%, lighten($deepBlue, 20%) 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    color: $ivoryWhite;
    border-radius: 4px;
    
    i {
      font-size: 18px;
    }
  }
  
  .borrow-badge {
    /deep/ .el-badge__content {
      background-color: $goldAccent;
    }
  }
}

/deep/ .el-table {
  .top-row {
    td {
      background-color: rgba($goldAccent, 0.1);
    }
  }
  
  .second-row {
    td {
      background-color: rgba($goldAccent, 0.05);
    }
  }
  
  .third-row {
    td {
      background-color: rgba($goldAccent, 0.02);
    }
  }
}

@media screen and (max-width: 768px) {
  .stats-dashboard {
    .chart-card {
      .chart-container {
        height: 220px;
        
        &.large {
          height: 280px;
        }
      }
    }
  }
}
</style> 